<template>
  <div class="table-box">
    <div class="table-search">
      <el-form :inline="true" :model="form">
        <el-form-item label="管理员账号">
          <el-input v-model="form.username" placeholder="管理员账号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="primary" plain @click="onAdd">新增</el-button>
          <el-button type="primary" plain @click="onExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card content-box">
      <div class="table">
        <el-table :data="tableData" border v-loading="loading">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column
            prop="phone"
            label="手机号"
            align="center"
            width="150"
          />
          <el-table-column
            prop="email"
            label="邮箱"
            align="center"
            width="200"
          />
          <el-table-column prop="gender" label="性别" align="center" />
          <el-table-column
            prop="is_active"
            label="是否启用"
            align="center"
            width="100"
            :formatter="formatter"
          />
          <el-table-column
            prop="is_staff"
            label="是否管理员"
            align="center"
            width="100"
            :formatter="formatter"
          />
          <el-table-column
            prop="is_superuser"
            label="是否超级管理员"
            align="center"
            width="130"
            :formatter="formatter"
          />
          <el-table-column
            prop="last_login"
            label="最后登录时间"
            align="center"
            width="200"
            :formatter="formatterUtcTime"
          />
          <el-table-column
            label="操作"
            align="center"
            width="200"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="primary"
                plain
                @click="onEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                type="primary"
                plain
                @click="handleSettings(scope.$index, scope.row)"
                >设置权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination">
          <el-pagination
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageable.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :destroy-on-close="true"
      title="用户信息"
      width="450px"
      @close="closeDialog"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="rules">
        <el-form-item
          label="账户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="dialogForm.username" />
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
          v-if="operateType === 'add'"
        >
          <el-input type="password" v-model="dialogForm.password" show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" v-else>
          <el-input type="password" v-model="dialogForm.password" show-password>
          </el-input>
        </el-form-item>

        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.email" />
        </el-form-item>

        <el-form-item label="证件号" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.id_number" />
        </el-form-item>
        <div class="flx-center">
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-switch
              v-model="dialogForm.gender"
              inline-prompt
              active-text="男"
              inactive-text="女"
            />
          </el-form-item>
          <el-form-item label="是否超级管理员" :label-width="formLabelWidth">
            <el-switch v-model="dialogForm.is_superuser" />
          </el-form-item>
        </div>
        <div class="flx-center">
          <el-form-item label="是否启用" :label-width="formLabelWidth">
            <el-switch v-model="dialogForm.is_active" />
          </el-form-item>
          <el-form-item label="是否管理员" :label-width="formLabelWidth">
            <el-switch v-model="dialogForm.is_staff" />
          </el-form-item>
        </div>

        <el-form-item label="id" style="display: none">
          <el-input v-model="dialogForm.id" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit" :loading="btnLoading">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限 -->
    <el-drawer v-model="drawer" direction="rtl" size="60%" @close="closeDrawer">
      <template #header="{ close, titleId, titleClass }">
        <h3 :id="titleId" :class="titleClass">配置组权限</h3>
        <div class="mr-30">
          <el-button type="primary" @click="savePermission"
            >保存权限
          </el-button>
        </div>
      </template>
      <div class="permission-box">
        <template v-for="item in allPermissions" :key="item.project_name">
          <div class="flex">
            <span>项目:</span
            ><span class="ml-20" style="font-weight: 700">{{
              item.project_name
            }}</span>
          </div>
          <div>
            <span>菜单:</span>
            <el-checkbox-group v-model="checkedData">
              <TreeCheckbox
                :permissions="item.permissions"
                @selectCheckbox="selectCheckbox"
              />
            </el-checkbox-group>
          </div>
        </template>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { formatter, exportToExcel, formatterUtcTime } from "@/utils/utils";
import {
  usersApi,
  usersAddApi,
  usersEditApi,
  permissionAllApi,
  editeUserPermissionApi,
  userPermissionApi,
} from "@/api/system/system";
import TreeCheckbox from "@/components/TreeCheckbox/index.vue";
const tableData = ref([]);
const dialogFormRef = ref(null);

const dialogFormVisible = ref(false);
const btnLoading = ref(false);
const operateType = ref(null);
const formLabelWidth = "120px";
const drawer = ref(null);
const checkedData = ref([]); //选中数据

const permissions = ref([]); //设置发送后端的权限组数据

const rowId = ref(null);

//权限菜单数据
const allPermissions = ref([]);
// 权限树
const treeMap = new Map();

const formData = {
  username: "",
};
const dialogFormData = {
  id: "",
  username: "",
  password: "",
  name: "",
  phone: "",
  email: "",
  gender: true,
  id_number: "",
  is_superuser: false,
  is_active: false,
  is_staff: false,
};
const form = reactive({ ...formData });
const dialogForm = reactive({ ...dialogFormData });
// 参数
const param = () => {
  return {
    page: pageable.pageNum,
    pagesize: pageable.pageSize,
    username: form.username,
  };
};

const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const loading = ref(false);

// 校验
const rules = {
  username: [{ required: true, message: "请输入账户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
};

// 格式化权限菜单数据
const formatPermissionData = (data) => {
  const arr = [];
  data.map((item) => {
    let obj = {
      project_name: item.project_name,
      project_code: item.project_code,
      permissions: [],
    };
    if (item.permissions.length > 0) {
      item.permissions.map((childrenItem) => {
        let children = {
          code: childrenItem.code,
          name: childrenItem.name,
          parentId: 0,
          method: [],
        };
        // 操作方法
        if (childrenItem.method && childrenItem.method.length > 0) {
          childrenItem.method.map((methodItem) => {
            let method = {
              code: childrenItem.code + methodItem.method,
              name: methodItem.name,
              parentId: childrenItem.code,
              code_name: methodItem.method,
            };
            children.method.push(method);
          });
        }
        obj.permissions.push(children);
      });
    }
    arr.push(obj);
  });

  return arr;
};
// 设置权限树
const formatPermissiontreeMap = (data) => {
  data.map((item) => {
    if (item.permissions && item.permissions.length > 0) {
      item.permissions.map((children) => {
        treeMap.set(children["code"], children);
      });
    }
  });
};

//获取全部权限

const getPermissionAll = async () => {
  try {
    const res = await permissionAllApi();
    allPermissions.value = formatPermissionData(res.data.all_permissions);
    formatPermissiontreeMap(allPermissions.value);
  } catch (error) {
    console.log(error);
  }
};

// 获取表格数据
const getTbaleData = async () => {
  loading.value = true;
  try {
    const res = await usersApi(param());
    loading.value = false;
    tableData.value = res.data.results;
    pageable.total = res.data.count;
  } catch (error) {
    loading.value = false;
  }
};
// 重置
const onReset = () => {
  Object.assign(form, formData);
};
// 查询
const onQuery = async () => {
  getTbaleData();
};
// 新增
const onAdd = () => {
  dialogFormVisible.value = true;
  operateType.value = "add";
};
//关闭弹窗
const closeDialog = () => {
  Object.assign(dialogForm, dialogFormData);
};

// 取消
const cancel = () => {
  dialogFormVisible.value = false;
  Object.assign(dialogForm, dialogFormData);
};
//设置组权限
const handleSettings = async (index, row) => {
  drawer.value = true;
  rowId.value = row.id;
  const res = await userPermissionApi(row.id);
  setSelectCheckbox(res.data.permissions);
  console.log(res);
};
// 设置选中的权限
const setSelectCheckbox = (data) => {
  const checkedDataArr = [];
  const permissionsArr = [];
  data.map((item) => {
    checkedDataArr.push(item.code);
    if (item.method && item.method.length > 0) {
      item.method.map((methodIem) => {
        checkedDataArr.push(item.code + methodIem.method);
        permissionsArr.push({
          code: item.code + methodIem.method,
          name: methodIem.name,
          parentId: item.code,
          code_name: methodIem.method,
        });
      });
    }
  });

  permissions.value = permissionsArr;

  checkedData.value = checkedDataArr;
};

// 关闭设置组权限
const closeDrawer = () => {
  drawer.value = false;
  checkedData.value = [];
  permissions.value = [];
  rowId.value = null;
};

// 表格按钮操作
const onEdit = (index, row) => {
  console.log(row);
  
  operateType.value = "edit";
  Object.assign(dialogForm, { ...row });
  dialogFormVisible.value = true;
};

// 提交
const submit = () => {
  dialogFormRef.value
    .validate()
    .then(async () => {
      try {
        const param = Object.assign({}, dialogForm);
        param.gender = param.gender ? "男" : "女";
        btnLoading.value = true;

        if (operateType.value == "add") {
          let res = await usersAddApi(param);
          ElMessage({
            message: res.message,
            type: "success",
          });
        } else if (operateType.value == "edit") {
          delete param.id
          delete param.last_login
          delete param.date_joined
          let res = await usersEditApi(dialogForm.id, param);
          ElMessage({
            message: res.message,
            type: "success",
          });
        }

        dialogFormVisible.value = false;
        btnLoading.value = false;
        getTbaleData();
      } catch (error) {
        btnLoading.value = false;
        dialogFormVisible.value = false;
      }
    })
    .catch((error) => {
      console.log(error);
    });
};

// 选中
const selectCheckbox = (item) => {
  const arr = Object.assign(checkedData.value, []);
  let findIndex = arr.indexOf(item.code);
  if (findIndex == -1) {
    deleteCheckedDataAndChildren(item);
  } else {
    addCheckedDataAndChildren(item);
    selectUpperLevel(item);
  }
};
// 选中
const addCheckedData = (data) => {
  const arr = Object.assign(checkedData.value, []);
  arr.push(data.code);
  checkedData.value = arr;
};
// 选中本级及子级
const addCheckedDataAndChildren = (data) => {
  permissions.value.push(data);
  const arr = Object.assign(checkedData.value, []);
  let findIndex = arr.findIndex((val) => val == data.code);
  // 自己本身
  if (data.code && findIndex == -1) {
    addCheckedData(data);
  }
  // 子节点
  if (data.children) {
    data.children.forEach((item) => {
      addCheckedDataAndChildren(item);
    });
  }
  // 操作方法
  if (data.method) {
    data.method.forEach((item) => {
      addCheckedDataAndChildren(item);
    });
  }
};
//选中上一级
const selectUpperLevel = (data) => {
  const arr = Object.assign(checkedData.value, []);
  // 拿到上级key
  let parentId = data.parentId;
  if (!parentId) {
    return;
  }
  // 从权限树对象 获取该父级对象
  let parentModule = treeMap.get(parentId);

  if (!parentModule) {
    return;
  }
  // 选中父级
  let parentIndex = arr.findIndex((e) => parentModule?.code === e);
  if (parentModule.code && parentIndex == -1) {
    addCheckedData(parentModule);
  }
  // 如果上级还有上级 则进行递归
  if (parentModule.parentId) {
    selectUpperLevel(parentModule);
  }
};

// 取消选中
const deleteCheckedData = (index) => {
  const arr = Object.assign(checkedData.value, []);
  arr.splice(index, 1);
  checkedData.value = arr;
};
// 取消选中本级以及子级
const deleteCheckedDataAndChildren = (data) => {
  // console.log("===>>删除", data);
  const newArray = [];
  permissions.value.filter((item) => {
    if (item.code != data.code) {
      newArray.push(item);
    }
  });
  permissions.value = newArray;
  const arr = Object.assign(checkedData.value, []);
  // 取消选中本级以及子级

  let findIndex = arr.findIndex((val) => val == data.code);

  if (findIndex != -1) {
    deleteCheckedData(findIndex, data);
  }
  if (data.children) {
    data.children.forEach((item) => {
      deleteCheckedDataAndChildren(item);
    });
  }
  if (data.method) {
    data.method.forEach((item) => {
      deleteCheckedDataAndChildren(item);
    });
  }
};

// 设置保存权限数据格式
// {
//   'mainnet':['add','delete']
// }
const setSavePermissionData = (permissions) => {
  const arr = [];
  const obj = {};
  permissions.map((item) => {
    if (item.parentId != 0 && !item.method) {
      if (!obj[item.parentId]) {
        obj[item.parentId] = [];
        obj[item.parentId].push(item.code_name);
      } else {
        obj[item.parentId].push(item.code_name);
      }
    }
  });
  for (let item in obj) {
    let method = obj[item];
    arr.push({ code: item, method: method.join(",") });
  }
  return arr;
};
// 保存权限
const savePermission = async () => {
  // if (!permissions.value.length) {
  //   ElMessage({
  //     message: "还未选择任何权限",
  //     type: "error",
  //   });
  //   return;
  // }
  console.log(permissions.value);
  if (rowId.value) {
    const arr = setSavePermissionData(permissions.value);
    const res = await editeUserPermissionApi(rowId.value, {
      permissions: arr,
    });
    ElMessage({
      message: res.message,
      type: "success",
    });
  }

  drawer.value = false;
};

// 条数
const handleSizeChange = (number) => {
  pageable.pageSize = number;
  getTbaleData();
};

// 页码
const handleCurrentChange = (number) => {
  pageable.pageNum = number;
  getTbaleData();
};
// 导出
const onExport = async () => {
  const data = Object.assign(param(), { export: 1 });
  const res = await usersApi(data);

  let head = {
    id: "ID",
    username: "用户名",
    name: "姓名",
    phone: "手机号",
    email: "邮箱",
    gender: "性别",
    is_active: "是否启用",
    is_staff: "是否管理员",
    is_superuser: "是否超级管理员",
    last_login: "最后登录时间",
  };
  exportToExcel(res.data.results, head, "管理员列表");
};

onMounted(async () => {
  getTbaleData();
  getPermissionAll();
});
</script>
<style>
.el-drawer__header {
  border-bottom: 1px solid #72767b;
  padding: var(--el-drawer-padding-primary);
}
.el-drawer__title {
  color: #000;
  font-size: 20px;
}
</style>
